package com.gurumades.jsonform.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.gurumades.jsonform.client.FormService;

public class FormServiceImpl extends RemoteServiceServlet implements
		FormService {
	private static String APPS_SAMPLE = "/WEB-INF/forms/";

	public String getForm(String formID) {
		try {
			URL url = getServletContext().getResource(APPS_SAMPLE+formID+".xml");
			InputStream streamResource = url.openStream();

			Unmarshaller marshaler = getUnMarshaller();
			JAXBElement o = (JAXBElement) marshaler
					.unmarshal(new InputStreamReader(streamResource));
			
			ObjectMapper mapper = new ObjectMapper();
	        AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
	        mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
	        mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
	        
	        String jsonString = mapper.defaultPrettyPrintingWriter().writeValueAsString(o.getValue());
			
			return jsonString;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		return null;

	}

	private Unmarshaller getUnMarshaller() {
		try {

			JAXBContext cxt = initContext();
			return cxt.createUnmarshaller();
		} catch (JAXBException e) {
			e.printStackTrace();

			return null;
		}
	}

	private JAXBContext initContext() throws JAXBException {
		JAXBContext cxt = JAXBContext
				.newInstance("com.gurumades.jsonform.server.forms");
		return cxt;
	}
}
